package chabernac.android.wordbattle.paint;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Picture;
import android.util.Log;
import android.util.SparseArray;
import chabernac.android.wordbattle.R;
import chabernac.android.wordbattle.WordRasterContext;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;

public class SVGFactory {
  private static SparseArray<Picture> mySVGCache = new SparseArray<Picture>();
  private static Map<String, Integer> myResourceMap = new HashMap<String, Integer>();

  /**
   * create a picture of a svg file
   * @param aResource the resource id of the SVG file
   * @return Picture
   */
  public static Picture createSVG(int aResource){
    if(mySVGCache.get(aResource) == null){
      SVG theSVGPicture = SVGParser.getSVGFromResource(WordRasterContext.getInstance().getContext().getResources(), aResource);
      mySVGCache.put(aResource, theSVGPicture.getPicture());
    }
    return mySVGCache.get(aResource);
  }

  /**
   * create a picture of a svg file given the name of the svg file in the /res/raw directory
   * 
   * @param aResourceName the resource name
   * @return Picture
   */
  public static Picture createSVG(String aResourceName){
    return createSVG(findRawResource(aResourceName));
  }

  public static int findRawResource(String aResourceName){
    if(!myResourceMap.containsKey(aResourceName)){
      try{
        Field theField = R.raw.class.getField(aResourceName);
        return (Integer)theField.get(null);
      }catch(Exception e){
        Log.e(SVGFactory.class.getName(), "Could not load resource with name '" + aResourceName + "'");
        //throw a runtime exception because we do not want having to handle an exception everywhere we call this method
        //normally a resource will alwasy be known
        throw new RuntimeException("Resource could not be loaded '" + aResourceName + "'");
      }
    }
    return myResourceMap.get(aResourceName);
  }
}
